import 'package:meco/common/index.dart';
import 'package:meco/common/models/official_content_model.dart';
import 'package:meco/common/data/services/database_service.dart';
import 'package:flutter/foundation.dart';

/// 官方内容删除观察者接口
abstract class OfficialContentDeleteObserver {
  /// 当官方内容被删除时调用
  void onOfficialContentDeleted(int contentId);
}

class OfficialContentRepository {
  // 观察者列表
  static final List<OfficialContentDeleteObserver> _observers = [];

  // 添加观察者
  static void addObserver(OfficialContentDeleteObserver observer) {
    if (!_observers.contains(observer)) {
      _observers.add(observer);
    }
  }

  // 移除观察者
  static void removeObserver(OfficialContentDeleteObserver observer) {
    _observers.remove(observer);
  }

  // 通知所有观察者官方内容已被删除
  static void notifyOfficialContentDeleted(int contentId) {
    for (var observer in _observers) {
      observer.onOfficialContentDeleted(contentId);
    }
  }

  final DatabaseService _databaseService = DatabaseService();
  final String _tableName = 'official_contents';
  final String _likesTableName = 'official_content_likes';
  final String _favoritesTableName = 'official_content_favorites';

  // 获取所有官方内容
  Future<List<OfficialContent>> getAllOfficialContents() async {
    final db = await _databaseService.database;

    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        orderBy: 'publish_time DESC',
      );

      if (maps.isEmpty) {
        return [];
      }

      return List.generate(maps.length, (i) {
        try {
          return OfficialContent.fromJson(maps[i]);
        } catch (e) {
          // 返回一个默认值，避免整个列表生成失败
          return OfficialContent(
            title: 'Error',
            description: 'Failed to parse data',
            publishTime: DateTime.now(),
          );
        }
      });
    } catch (e) {
      return [];
    }
  }

  // 获取单个官方内容
  Future<OfficialContent?> getOfficialContentById(int id) async {
    final db = await _databaseService.database;

    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'id = ?',
        whereArgs: [id],
      );

      if (maps.isEmpty) {
        return null;
      }

      return OfficialContent.fromJson(maps.first);
    } catch (e) {
      return null;
    }
  }

  // 更新官方内容
  Future<bool> updateOfficialContent(OfficialContent content) async {
    if (content.id == null) {
      return false;
    }

    final db = await _databaseService.database;
    final contentMap = content.toJson();
    contentMap['updated_at'] = DateTime.now().millisecondsSinceEpoch;

    try {
      final result = await db.update(
        _tableName,
        contentMap,
        where: 'id = ?',
        whereArgs: [content.id],
      );
      return result > 0;
    } catch (e) {
      return false;
    }
  }

  // 删除官方内容
  Future<bool> deleteOfficialContent(int contentId) async {
    final db = await _databaseService.database;
    try {
      // 从数据库中删除官方内容
      final result = await db.delete(
        _tableName,
        where: 'id = ?',
        whereArgs: [contentId],
      );

      // 如果删除成功，通知所有观察者
      if (result > 0) {
        notifyOfficialContentDeleted(contentId);
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('删除官方内容失败: $e');
      return false;
    }
  }

  // 创建官方内容
  Future<int> createOfficialContent(OfficialContent content) async {
    final db = await _databaseService.database;
    final now = DateTime.now().millisecondsSinceEpoch;

    final contentMap = content.toJson();
    contentMap['created_at'] = now;
    contentMap['updated_at'] = now;

    try {
      return await db.insert(_tableName, contentMap);
    } catch (e) {
      return -1;
    }
  }

  // 获取用户收藏的官方内容
  Future<List<OfficialContent>> getFavoritedOfficialContents(int userId) async {
    try {
      final db = await _databaseService.database;
      final List<Map<String, dynamic>> maps = await db.rawQuery(
        '''
        SELECT c.* FROM $_tableName c
        INNER JOIN $_favoritesTableName f ON c.id = f.official_content_id
        WHERE f.user_id = ?
        ORDER BY f.created_at DESC
      ''',
        [userId],
      );

      return List.generate(
        maps.length,
        (i) => OfficialContent.fromJson(maps[i]),
      );
    } catch (e) {
      print('获取用户收藏官方内容错误: $e');
      return [];
    }
  }

  // 获取用户点赞的官方内容
  Future<List<OfficialContent>> getLikedOfficialContents(int userId) async {
    try {
      final db = await _databaseService.database;
      final List<Map<String, dynamic>> maps = await db.rawQuery(
        '''
        SELECT c.* FROM $_tableName c
        INNER JOIN $_likesTableName l ON c.id = l.official_content_id
        WHERE l.user_id = ?
        ORDER BY l.created_at DESC
      ''',
        [userId],
      );

      return List.generate(
        maps.length,
        (i) => OfficialContent.fromJson(maps[i]),
      );
    } catch (e) {
      print('获取用户点赞官方内容错误: $e');
      return [];
    }
  }

  // 添加收藏
  Future<bool> favoriteOfficialContent(int userId, int contentId) async {
    final db = await _databaseService.database;

    try {
      // 检查是否已经收藏
      final checkResult = await db.query(
        _favoritesTableName,
        where: 'user_id = ? AND official_content_id = ?',
        whereArgs: [userId, contentId],
      );

      if (checkResult.isNotEmpty) {
        // 已收藏
        return true;
      }

      // 添加收藏记录
      await db.insert(_favoritesTableName, {
        'user_id': userId,
        'official_content_id': contentId,
        'created_at': DateTime.now().millisecondsSinceEpoch,
      });

      // 更新内容收藏计数
      await db.rawUpdate(
        '''
        UPDATE $_tableName
        SET favorite_count = favorite_count + 1
        WHERE id = ?
      ''',
        [contentId],
      );

      return true;
    } catch (e) {
      print('添加官方内容收藏错误: $e');
      return false;
    }
  }

  // 取消收藏
  Future<bool> unfavoriteOfficialContent(int userId, int contentId) async {
    final db = await _databaseService.database;

    try {
      // 删除收藏记录
      final deleteResult = await db.delete(
        _favoritesTableName,
        where: 'user_id = ? AND official_content_id = ?',
        whereArgs: [userId, contentId],
      );

      if (deleteResult > 0) {
        // 更新内容收藏计数
        await db.rawUpdate(
          '''
          UPDATE $_tableName
          SET favorite_count = favorite_count - 1
          WHERE id = ? AND favorite_count > 0
        ''',
          [contentId],
        );
      }

      return deleteResult > 0;
    } catch (e) {
      print('取消官方内容收藏错误: $e');
      return false;
    }
  }

  // 添加点赞
  Future<bool> likeOfficialContent(int userId, int contentId) async {
    final db = await _databaseService.database;

    try {
      // 检查是否已经点赞
      final checkResult = await db.query(
        _likesTableName,
        where: 'user_id = ? AND official_content_id = ?',
        whereArgs: [userId, contentId],
      );

      if (checkResult.isNotEmpty) {
        // 已点赞
        return true;
      }

      // 添加点赞记录
      await db.insert(_likesTableName, {
        'user_id': userId,
        'official_content_id': contentId,
        'created_at': DateTime.now().millisecondsSinceEpoch,
      });

      // 更新内容点赞计数
      await db.rawUpdate(
        '''
        UPDATE $_tableName
        SET like_count = like_count + 1
        WHERE id = ?
      ''',
        [contentId],
      );

      return true;
    } catch (e) {
      print('添加官方内容点赞错误: $e');
      return false;
    }
  }

  // 取消点赞
  Future<bool> unlikeOfficialContent(int userId, int contentId) async {
    final db = await _databaseService.database;

    try {
      // 删除点赞记录
      final deleteResult = await db.delete(
        _likesTableName,
        where: 'user_id = ? AND official_content_id = ?',
        whereArgs: [userId, contentId],
      );

      if (deleteResult > 0) {
        // 更新内容点赞计数
        await db.rawUpdate(
          '''
          UPDATE $_tableName
          SET like_count = like_count - 1
          WHERE id = ? AND like_count > 0
        ''',
          [contentId],
        );
      }

      return deleteResult > 0;
    } catch (e) {
      print('取消官方内容点赞错误: $e');
      return false;
    }
  }
}
